package com.atguigu.srb.core.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.atguigu.srb.common.exception.Assert;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.core.enums.BorrowInfoStatusEnum;
import com.atguigu.srb.core.enums.BorrowerStatusEnum;
import com.atguigu.srb.core.enums.UserBindEnum;
import com.atguigu.srb.core.mapper.BorrowInfoMapper;
import com.atguigu.srb.core.mapper.BorrowerMapper;
import com.atguigu.srb.core.mapper.IntegralGradeMapper;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.pojo.entity.BorrowInfo;
import com.atguigu.srb.core.pojo.entity.Borrower;
import com.atguigu.srb.core.pojo.entity.IntegralGrade;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.pojo.vo.BorrowInfoApprovalVO;
import com.atguigu.srb.core.pojo.vo.BorrowerDetailVO;
import com.atguigu.srb.core.service.BorrowInfoService;
import com.atguigu.srb.core.service.BorrowerService;
import com.atguigu.srb.core.service.DictService;
import com.atguigu.srb.core.service.LendService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author javaCode
 * @since 2025-07-19
 */
@RequiredArgsConstructor
@Slf4j
@Service
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {

    // 用户基本信息 Mapper 接口
    private final UserInfoMapper userInfoMapper;

    // 积分等级表 Mapper 接口
    private final IntegralGradeMapper integralGradeMapper;

    // 数据字典 服务类
    private final DictService dictService;

    // 借款人 Mapper 接口
    private final BorrowerMapper borrowerMapper;

    // 借款人 服务类
    private final BorrowerService borrowerService;
    private final LendService lendService;

    /**
     * 获取借款额度
     */
    @Override
    public BigDecimal getBorrowAmount(Long userId) {
        log.info("开始查询用户ID为{}的借款额度", userId);

        // 获取用户积分
        UserInfo userInfo = userInfoMapper.selectById(userId);
        Assert.notNull(userInfo, ResponseEnum.LOGIN_MOBILE_ERROR);

        // 用户积分
        Integer integral = userInfo.getIntegral();
        log.info("用户ID为{}的积分是：{}", userId, integral);

        // 构建查询条件并添加非空校验
        LambdaQueryWrapper<IntegralGrade> wrapper = new LambdaQueryWrapper<>();
        wrapper.le(IntegralGrade::getIntegralStart, integral).ge(IntegralGrade::getIntegralEnd, integral);

        IntegralGrade integralGrade = integralGradeMapper.selectOne(wrapper);

        if (integralGrade == null) {
            log.info("用户ID为{}的积分未匹配到对应的借款额度等级，返回0", userId);
            return BigDecimal.ZERO;
        }

        log.info("用户ID为{}的借款额度是：{}", userId, integralGrade.getBorrowAmount());
        return integralGrade.getBorrowAmount();
    }

    /**
     * 获取借款状态
     */
    @Override
    public Integer getBorrowInfoStatus(Long userId) {
        // 构建查询条件，查找该用户的借款记录
        LambdaQueryWrapper<BorrowInfo> wrapper = new LambdaQueryWrapper<BorrowInfo>().eq(BorrowInfo::getUserId, userId).select(BorrowInfo::getStatus);

        List<Object> objects = baseMapper.selectObjs(wrapper);

        // 记录查询结果数量，便于排查问题
        log.info("查询用户ID={}的借款状态，返回记录数：{}", userId, objects.size());

        if (CollectionUtils.isEmpty(objects)) {
            // 借款人尚未提交信息
            log.info("用户ID={}尚未提交借款信息，返回状态：{}", userId, BorrowInfoStatusEnum.NO_AUTH.getStatus());
            return BorrowInfoStatusEnum.NO_AUTH.getStatus();
        }

        // 处理查询结果
        Object firstResult = objects.get(0);
        if (firstResult == null) {
            log.warn("用户ID={}的借款状态为null，返回状态：{}", userId, BorrowInfoStatusEnum.NO_AUTH.getStatus());
            return BorrowInfoStatusEnum.NO_AUTH.getStatus();
        }

        // 确保类型安全
        if (firstResult instanceof Integer) {
            Integer status = (Integer) firstResult;
            log.info("用户ID={}的借款状态为：{}", userId, status);
            return status;
        } else {
            // 记录异常情况并返回默认状态
            log.error("用户ID={}的借款状态类型异常，期望Integer，实际类型：{}", userId, firstResult.getClass().getName());
            return BorrowInfoStatusEnum.NO_AUTH.getStatus();
        }
    }

    /**
     * 提交借款申请
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveBorrowInfo(BorrowInfo borrowInfo, Long userId) {
        log.info("开始处理用户ID={}的借款申请", userId);

        // 获取用户信息并检查是否存在
        UserInfo userInfo = userInfoMapper.selectById(userId);
        Assert.notNull(userInfo, ResponseEnum.USER_NOT_EXIST_ERROR);

        // 校验用户绑定状态
        Assert.isTrue(userInfo.getBindStatus().intValue() == UserBindEnum.BIND_OK.getStatus().intValue(), ResponseEnum.USER_NO_BIND_ERROR);

        // 校验用户借款权限状态
        Assert.isTrue(userInfo.getBorrowAuthStatus().intValue() == BorrowerStatusEnum.AUTH_OK.getStatus().intValue(), ResponseEnum.USER_NO_AMOUNT_ERROR);

        // 获取用户借款额度并校验申请金额
        BigDecimal borrowAmount = this.getBorrowAmount(userId);
        Assert.isTrue(borrowInfo.getAmount().compareTo(borrowAmount) <= 0, ResponseEnum.USER_AMOUNT_LESS_ERROR);

        // 校验借款金额有效性
        Assert.isTrue(borrowInfo.getAmount().compareTo(BigDecimal.ZERO) > 0, ResponseEnum.BORROW_AMOUNT_INVALID_ERROR);

        // 设置借款信息
        borrowInfo.setUserId(userId);

        // 百分比转小数 (例如: 10% → 0.1)
        borrowInfo.setBorrowYearRate(convertPercentToDecimal(borrowInfo.getBorrowYearRate()));

        // 设置初始状态为"审核中"
        borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());

        // 保存借款申请
        baseMapper.insert(borrowInfo);
        log.info("用户ID={}的借款申请已提交，申请金额={}，申请ID={}", userId, borrowInfo.getAmount(), borrowInfo.getId());
    }

    /**
     * 借款信息列表
     */
    @Override
    public List<BorrowInfo> selectList() {
        // 查询借款信息列表
        List<BorrowInfo> borrowInfoList = baseMapper.selectBorrowInfoList();

        // 处理空列表情况
        if (borrowInfoList == null || borrowInfoList.isEmpty()) {
            return Collections.emptyList();
        }

        // 使用Stream和Lambda表达式处理列表
        return borrowInfoList.stream().peek(borrowInfo -> {
            Map<String, String> additionalInfo = new HashMap<>();

            // 获取还款方式
            String returnMethod = dictService.getNameByParentDictCodeAndValue("returnMethod", borrowInfo.getReturnMethod());
            additionalInfo.put("returnMethod", returnMethod != null ? returnMethod : "未知还款方式");

            // 获取资金用途
            String moneyUse = dictService.getNameByParentDictCodeAndValue("moneyUse", borrowInfo.getMoneyUse());
            additionalInfo.put("moneyUse", moneyUse != null ? moneyUse : "未知用途");

            // 获取借款状态
            String status = BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus());
            additionalInfo.put("status", status != null ? status : "未知状态");

            // 将补充信息放入param
            borrowInfo.getParam().putAll(additionalInfo);
        }).collect(Collectors.toList());
    }

    /**
     * 获取借款信息
     */
    @Override
    public Map<String, Object> getBorrowInfoDetail(Long id) {
        // 查询借款对象
        BorrowInfo borrowInfo = baseMapper.selectById(id);
        if (borrowInfo == null) {
            throw new RuntimeException("借款信息不存在，ID: " + id);
        }

        // 填充借款信息中的字典项
        String returnMethod = dictService.getNameByParentDictCodeAndValue("returnMethod", borrowInfo.getReturnMethod());
        String moneyUse = dictService.getNameByParentDictCodeAndValue("moneyUse", borrowInfo.getMoneyUse());
        String status = BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus());

        borrowInfo.getParam().put("returnMethod", returnMethod);
        borrowInfo.getParam().put("moneyUse", moneyUse);
        borrowInfo.getParam().put("status", status);

        // 查询借款人信息
        Borrower borrower = borrowerMapper.selectOne(new LambdaQueryWrapper<Borrower>().eq(Borrower::getUserId, borrowInfo.getUserId()));
        if (borrower == null) {
            throw new RuntimeException("借款人信息不存在，用户ID: " + borrowInfo.getUserId());
        }

        // 获取借款人详情
        BorrowerDetailVO borrowerDetailVO = borrowerService.getBorrowerDetailVOById(borrower.getId());

        // 组装结果
        Map<String, Object> result = new HashMap<>();
        result.put("borrowInfo", borrowInfo);
        result.put("borrower", borrowerDetailVO);

        return result;
    }

    /**
     * 审批借款信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void approval(BorrowInfoApprovalVO borrowInfoApprovalVO) {
        // 修改借款信息状态
        Long borrowInfoId = borrowInfoApprovalVO.getId();

        BorrowInfo borrowInfo = baseMapper.selectById(borrowInfoId);
        borrowInfo.setStatus(borrowInfoApprovalVO.getStatus());
        baseMapper.updateById(borrowInfo);

        // 审核通过则创建标的
        if (borrowInfoApprovalVO.getStatus().intValue() == BorrowInfoStatusEnum.CHECK_OK.getStatus().intValue()) {
            // 创建标的
            lendService.createLend(borrowInfoApprovalVO, borrowInfo);
        }
    }

    /**
     * 将百分比形式的BigDecimal转换为小数形式
     * 例如: 10 → 0.1
     */
    private BigDecimal convertPercentToDecimal(BigDecimal percentValue) {
        return percentValue.divide(new BigDecimal(100), 8, RoundingMode.HALF_UP);
    }
}
